#include <boost/bind.hpp>
#include <firebird/message/message.hpp>
#include <firebird/message/message_path.hpp>
#include <firebird/protocol/protocol.hpp>
#include <firebird/service/service_constants.hpp>
#include <firebird/service/monitor_service.hpp>
#include <firebird/option/options.hpp>
namespace firebird {

monitor_service::monitor_service(bus& bus) : service(bus) {
	session_timeout_ = get_option("moni_service","session_timeout").as<int>(30);
}

int monitor_service::calc_online(int srv_id, int func_id) {
	int online = 0;
	BOOST_FOREACH(user_status_map::value_type& i, users_status_) {
		std::time_t now;
		std::time(&now);
		user_status& us = i.second;
		if (((srv_id == 0) || 
				(srv_id == us.last_operation.first && (func_id == 0 || func_id == us.last_operation.second)))
			&& (now - us.last_operation_time < session_timeout_)) {
			online++;
		}
	}
	
	return online;
}
	
void monitor_service::handle_message(message& msg) {
	if (msg.source()[0] == st_transport) {
		int biz_srvid = msg.destination()[1];
		int biz_funcid = msg.destination()[2];

		Envelope* envelope = (Envelope*)&msg.data()[0];
		Header* header = (Header*)(&msg.data()[sizeof(Envelope)]);
		
		user_status_map::iterator it = users_status_.find(header->qwUserId);
		if (it == boost::end(users_status_)) {
			user_status us;
			std::time(&us.last_login_time);
			it = users_status_.insert(std::make_pair(header->qwUserId, us)).first;
		}
		
		std::time(&it->second.last_operation_time);
		it->second.last_operation.first = biz_srvid;
		it->second.last_operation.second = biz_funcid;
	}
}

}